<!--端口检测-->
<template>
    <div class="mainDataCollect">
        <!-- 左侧 -->
        <div class="left">
            <el-card style="height: 100%; overflow: auto" shadow="never">
                <el-input
                        v-model="searchGroupParams.taskGroupName"
                        @blur="
            searchGroupParams.taskGroupName =
              searchGroupParams.taskGroupName!.trim()
          "
                        style="width: 70%"
                        placeholder="请输入采集器名称"
                        clearable
                >
                    <template #append>
                        <el-button type="primary" :icon="Search" @click="getGroupList"/>
                    </template>
                </el-input>

                <el-button
                        style="margin-top: 20px"
                        :icon="MyPlusMinus"
                        @click="openOrUpdateGroupForm"
                >新增采集器分组
                </el-button>

                <div
                        class="hello"
                        style="
            margin-top: 20px;
            width: 100px;
            display: flex;
            justify-content: last baseline;
            align-items: center;
          "
                        @click="openAllIcon"
                >
                    <div style="cursor: pointer">
                        <MyPlus v-if="!allFlag"/>
                        <MyMinus v-else/>
                    </div>
                    <span style="margin-left: 5px; cursor: pointer">全部</span>
                </div>
                <!-- @vue-ignore -->
                <el-table
                        v-if="allFlag"
                        :data="groupList"
                        :row-style="(val) => {
            return {
                'background-color': val.row.id == current_row_key ?  '#ced4da' : '#ffffff'
            }
          }"
                        :style="{ width: '100%' }"
                        :show-header="false"
                        style="width: 80%; margin-left: 50px; border: none"
                        :cell-style="{ border: 'none' }"
                        size="small"
                        v-loading="tableLoading"
                        @row-dblclick="
            (val) => {
              collectParams.taskGroupIds = [0];
              current_row_key = -100;
              getCollectList();
            }
          "
                        @row-click="
            (val) => {
              current_row_key = val.id;
              collectParams.taskGroupIds = [val.id];
              getCollectList();
            }
          "
                >
                    <el-table-column prop="taskGroupName" label="分组名称" width="100"/>
                    <el-table-column>
                        <template #default="scope">
                            <el-icon
                                    @click="openOrUpdateGroupForm(false, scope.row)"
                                    style="margin-left: 20px; cursor: pointer"
                            >
                                <EditPen/>
                            </el-icon>
                            <el-popconfirm
                                    confirm-button-text="确定"
                                    cancel-button-text="取消"
                                    :icon="Delete"
                                    icon-color="#626AEF"
                                    :title="`你确定要${scope.row.taskGroupName}删除吗?`"
                                    @confirm="deleteGroup(scope.row.id)"
                            >
                                <template #reference>
                                    <el-icon style="margin-left: 20px; cursor: pointer">
                                        <Delete/>
                                    </el-icon>
                                </template>
                            </el-popconfirm>

                            <el-tooltip effect="dark" content="新增采集器" placement="top">
                                <el-icon
                                        style="margin-left: 20px; cursor: pointer"
                                        @click="
                    openOrUpdateCollectForm(true, { taskGroupId: scope.row.id })
                  "
                                >
                                    <Plus/>
                                </el-icon>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分割线 -->
        <el-divider
                direction="vertical"
                border-style="dashed"
                style="height: calc(100% - 40px); margin-top: 20px; margin-bottom: 20px"
        />

        <!-- 右侧 -->
        <div class="right">
            <el-card shadow="never">
                <el-form ref="formRef" label-width="auto" :inline="true">
                    <el-form-item label="任务名称:" prop="name">
                        <el-input
                                placeholder="请输入任务名称"
                                v-model="collectParams.taskName"
                                style="width: 150px"
                                clearable
                        />
                    </el-form-item>
                    <el-form-item label="采集任务类型:" prop="zone">
                        <el-select
                                v-model="collectParams.taskType"
                                placeholder="请选择"
                                style="width: 150px"
                                clearable
                        >
                            <el-option label="mqtt" :value="1"/>
                            <el-option label="扫描文件" :value="2"/>
                            <el-option label="tcp-server" :value="3"/>
                            <el-option label="tcp-client" :value="4"/>
                            <el-option label="CDM专用采集" :value="5"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注:" prop="time">
                        <el-input
                                clearable
                                placeholder="请输入备注信息"
                                style="width: 150px"
                                v-model="collectParams.remark"
                        />
                        <el-button
                                style="margin-left: 100px"
                                :icon="Search"
                                @click="getCollectList"
                        >搜索
                        </el-button>
                        <el-button
                                style="margin-left: 20px"
                                :icon="Refresh"
                                type="primary"
                                @click="reset"
                        >重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
            <!--
                    :gutter:设置列之间的间隔
                    :xs 设置断点小于 768px 的屏幕的列数
                    :sm 设置断点大于等于 768px 小于 992px 的屏幕的列数
                    :md 设置断点大于等于 992px 小于 1200px 的屏幕的列数
                    :lg 设置断点大于等于 1200px 的屏幕的列数
                  -->
            <div style="flex: 1">
                <el-row :gutter="20">
                    <!--xs: 24, sm: 12, md: 8, lg: 6表示
                              在小于 768px 的屏幕上每行显示 24 个列
                              在大于等于 768px 小于 992px 的屏幕上每行显示 12 个列
                              在大于等于 992px 小于 1200px 的屏幕上每行显示 8 个列
                              在大于等于 1200px 的屏幕上每行显示 6 个列
                            -->
                    <el-col
                            :xs="24"
                            :sm="24"
                            :md="24"
                            :lg="12"
                            v-for="item in collectList"
                            :key="item"
                    >
                        <!--grid-content是el-col的子元素
                                    ep-bg-purple是el-col的class
                                    class="grid-content ep-bg-purple"是将el-col的class设置为grid-content ep-bg-purple
                                  -->
                        <el-card shadow="hover">
                            <div style="display: flex; width: 100%">
                                <!-- @vue-ignore -->
                                <el-switch
                                        :disabled="!item.flag"
                                        v-model="item.taskStatus"
                                        @change="(val) => switchChange(val, item)"
                                />
                                <div
                                        style="
                    margin-left: 10px;
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                  "
                                >
                                    <div>
                                        <div style="margin-bottom: 10px; display: block">
                                            {{ item.taskName }}
                                        </div>
                                        <div style="width: 100%; display: flex">
                                            <div v-if="item.taskType == 1">MQTT</div>
                                            <div v-else-if="item.taskType == 2">扫描文件</div>
                                            <div v-else-if="item.taskType == 3">TCP-server</div>
                                            <div v-else-if="item.taskType == 4">TCP-client</div>
                                            <div v-else-if="item.taskType == 5">CDM扫描</div>
                                            <div style="margin-left: 50px">
                                                组名 :
                                                {{
                                                groupList?.find((v) => v.id == item.taskGroupId)
                                                    ?.taskGroupName
                                                }}
                                            </div>
                                        </div>
                                    </div>

                                    <div
                                            style="
                      height: 50%;
                      display: flex;
                      width: 100px;
                      justify-content: space-between;
                      align-items: center;
                    "
                                    >
                                        <!-- 查看采集器 -->
                                        <!-- @vue-ignore -->
                                        <el-icon
                                                :size="20"
                                                style="
                        justify-content: right;
                        cursor: pointer;
                        margin-top: 10px;
                        transition: transform 0.3s;
                      "
                                                @click="toCollectPage(item?.id, item.taskGroupId)"
                                                @mouseenter="
                        (event) => (event.target.style.transform = 'scale(1.4)')
                      "
                                                @mouseleave="
                        (event) => (event.target.style.transform = 'scale(1)')
                      "
                                        >
                                            <View/>
                                        </el-icon>
                                        <!-- 修改采集器 -->
                                        <!-- @vue-ignore -->
                                        <el-icon
                                                :size="20"
                                                style="
                        justify-content: right;
                        cursor: pointer;
                        margin-top: 10px;
                        transition: transform 0.3s;
                      "
                                                @click="openOrUpdateCollectForm(false, item)"
                                                @mouseenter="
                        (event) => (event.target.style.transform = 'scale(1.4)')
                      "
                                                @mouseleave="
                        (event) => (event.target.style.transform = 'scale(1)')
                      "
                                        >
                                            <Edit/>
                                        </el-icon>

                                        <!-- 删除采集器 -->
                                        <!-- @vue-ignore -->
                                        <el-popconfirm
                                                confirm-button-text="确定"
                                                cancel-button-text="取消"
                                                :icon="Delete"
                                                icon-color="#FF0000"
                                                :title="`确定要删除${item.taskName}采集器吗?`"
                                                @confirm="deleteCollect(item.id!)"
                                        >
                                            <template #reference>
                                                <!-- @vue-ignore -->
                                                <el-icon
                                                        :size="20"
                                                        style="
                            justify-content: right;
                            cursor: pointer;
                            margin-top: 10px;
                            transition: transform 0.3s;
                          "
                                                        @mouseenter="
                            (event) =>
                              (event.target.style.transform = 'scale(1.4)')
                          "
                                                        @mouseleave="
                            (event) =>
                              (event.target.style.transform = 'scale(1)')
                          "
                                                >
                                                    <Delete/>
                                                </el-icon>
                                            </template>
                                        </el-popconfirm>
                                    </div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <el-pagination
                    style="justify-content: right"
                    v-model:current-page="collectParams.pageNum"
                    v-model:page-size="collectParams.pageSize"
                    :size="size"
                    :background="background"
                    layout="total, prev, pager, next, jumper"
                    :total="totalNum"
                    @current-change="getCollectList"
            />
        </div>

        <!-- 新增或更新分组 -->
        <el-dialog
                v-model="groupForm.flag"
                :title="groupForm.title"
                draggable
                width="50vw"
                style="
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      "
        >
            <el-form
                    ref="groupFormRef"
                    :model="groupForm.data"
                    :rules="groupForm.rules"
                    label-width="auto"
            >
                <el-form-item label="名称:" prop="taskGroupName">
                    <el-input
                            v-model="groupForm.data.taskGroupName"
                            style="width: 20vw"
                            @blur="
              groupForm.data.taskGroupName = groupForm.data.taskGroupName.trim()
            "
                            placeholder="请输入组名"
                    />
                </el-form-item>
                <el-form-item label="备注:" prop="remark">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 5, maxRows: 10 }"
                            style="width: 20vw"
                            v-model="groupForm.data.remark"
                            placeholder="请输入备注"
                            @blur="groupForm.data.remark = groupForm.data.remark!.trim()"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div
                        style="
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
          "
                >
                    <el-button @click="addOrUpdateGroup" type="primary">确定</el-button>
                    <el-button @click="groupForm.flag = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 新增或更新采集器 -->
        <el-dialog
                v-model="collectForm.flag"
                :title="collectForm.title"
                draggable
                width="40vw"
                style="
        display: flex;
        overflow: auto;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      "
        >
            <el-scrollbar height="50vh" width="100%">
                <el-form
                        ref="collectFormRef"
                        :model="collectForm.data"
                        :rules="collectForm.rules"
                        label-width="auto"
                >
                    <el-form-item label="名称:" prop="taskName">
                        <el-input
                                v-model="collectForm.data.taskName"
                                style="width: 20vw"
                                @blur="
                collectForm.data.taskName = collectForm.data.taskName!.trim()
              "
                                placeholder="请输入采集器名称"
                        />
                    </el-form-item>
                    <el-form-item label="采集方式:" prop="taskType">
                        <el-select
                                v-model="collectForm.data.taskType"
                                placeholder="请选择采集方式"
                        >
                            <el-option label="MQTT" :value="1"/>
                            <el-option label="扫描文件" :value="2"/>
                            <el-option label="Tcp-Server" :value="3"/>
                            <el-option label="Tcp-Client" :value="4"/>
                            <el-option label="CDM专用扫描文件" :value="5"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="collectForm.title=='新增采集器'" label="解析协议模板">
                        <el-select :clearable="true" v-model="collectForm.data.resolveId" placeholder="请选择">
                            <el-option v-for="item in dataResolverTempList" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="collectForm.title=='新增采集器'" label="上报协议模板">
                        <el-select :clearable="true" v-model="collectForm.data.handlerId" placeholder="请选择">
                            <el-option v-for="item in dataForwardParseTempList" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                            v-if="
              collectForm.data.taskType == 2 || collectForm.data.taskType == 5
            "
                            label="文件路径:"
                            prop="collectFilePath"
                    >
                        <el-input
                                @blur="
                collectForm.data.collectFilePath =
                  collectForm.data.collectFilePath!.trim()
              "
                                v-model="collectForm.data.collectFilePath"
                                placeholder="请输入文件路径"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType != 1 && collectForm.data.taskType"
                            label="采集频率:"
                            prop="taskFreqCorn"
                    >
                        <!--            <el-input-->
                        <!--              v-model="collectForm.data.taskFreqCorn"-->
                        <!--              @blur="-->
                        <!--                collectForm.data.taskFreqCorn =-->
                        <!--                  collectForm.data.taskFreqCorn!.trim()-->
                        <!--              "-->
                        <!--              placeholder="请输入采集频率(corn表达式)"-->
                        <!--            />-->
                        <el-select
                                v-model="collectForm.data.taskFreqCorn"
                                placeholder="请选择采集频率"
                        >
                            <el-option label="1(分钟)" :value="'*/1 * * * *'"/>
                            <el-option label="2(分钟)" :value="'*/2 * * * *'"/>
                            <el-option label="5(分钟)" :value="'*/5 * * * *'"/>
                            <el-option label="10(分钟)" :value="'*/10 * * * *'"/>
                            <el-option label="30(分钟)" :value="'*/30 * * * *'"/>
                            <el-option label="1(小时)" :value="'0 * * * *'"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item
                            v-if="
              collectForm.data.taskType == 2 ||
              collectForm.data.taskType == 5 ||
              collectForm.data.taskType == 6
            "
                            label="采集起始行数:"
                            prop="collectReadLine"
                    >
                        <el-input
                                v-model.number="collectForm.data.collectReadLine"
                                placeholder="请输入读取行数"
                        />
                    </el-form-item>

                    <el-form-item label="分组名称:" prop="taskGroupId">
                        <el-select
                                v-model="collectForm.data.taskGroupId"
                                placeholder="请选择"
                        >
                            <el-option
                                    v-for="item in groupList"
                                    :label="item.taskGroupName"
                                    :value="item.id"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item
                            v-if="collectForm.data.taskType == 3"
                            label="监听端口:"
                            prop="listenerPort"
                    >
                        <el-input
                                v-model.number="collectForm.data.listenerPort"
                                placeholder="请输入监听端口"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="
              collectForm.data.taskType == 3 || collectForm.data.taskType == 4
            "
                            label="指令hex字符串:"
                            prop="hexOrderString"
                    >
                        <el-input
                                type="textarea"
                                @blur="
                collectForm.data.hexOrderString =
                  collectForm.data.hexOrderString!.trim()
              "
                                v-model="collectForm.data.hexOrderString"
                                placeholder="输入指令字符串,多个用逗号分隔"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType == 4"
                            label="TCP目标地址:"
                            prop="tarTcpUrl"
                    >
                        <el-input
                                @blur="
                collectForm.data.tarTcpUrl = collectForm.data.tarTcpUrl!.trim()
              "
                                v-model="collectForm.data.tarTcpUrl"
                                placeholder="请输入转发地址"
                        />
                    </el-form-item>


                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="MQTT URL:"
                            prop="mqttUrl"
                    >
                        <el-input
                                @blur="
                collectForm.data.mqttUrl = collectForm.data.mqttUrl!.trim()
              "
                                v-model="collectForm.data.mqttUrl"
                                placeholder="请输入MQTT URL"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="主题:"
                            prop="topic"
                    >
                        <el-input
                                @blur="collectForm.data.topic = collectForm.data.topic!.trim()"
                                v-model="collectForm.data.topic"
                                placeholder="请输入主题"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="clientId:"
                            prop="clientId"
                    >
                        <el-input
                                v-model="collectForm.data.clientId"
                                @blur="
                collectForm.data.clientId =
                  collectForm.data.clientId!.trim() || ''
              "
                                placeholder="请输入客户端ID"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="用户名:"
                            prop="userName"
                    >
                        <el-input
                                @blur="
                collectForm.data.userName = collectForm.data.userName!.trim()
              "
                                v-model="collectForm.data.userName"
                                placeholder="请输入用户名"
                        />
                    </el-form-item>
                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="密码:"
                            prop="password"
                    >
                        <el-input
                                @blur="
                collectForm.data.password = collectForm.data.password!.trim()
              "
                                v-model="collectForm.data.password"
                                placeholder="请输入密码"
                        />
                    </el-form-item>

                    <el-form-item
                            v-if="collectForm.data.taskType == 1"
                            label="QoS:"
                            prop="qos"
                    >
                        <el-select
                                v-model.number="collectForm.data.qos"
                                placeholder="请选择QoS"
                        >
                            <el-option label="QoS0" :value="0"/>
                            <el-option label="QoS1" :value="1"/>
                            <el-option label="QoS2" :value="2"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注:" prop="remark">
                        <el-input
                                type="textarea"
                                :autosize="{ minRows: 5, maxRows: 10 }"
                                v-model="collectForm.data.remark"
                                placeholder="请输入备注"
                        />
                    </el-form-item>

                    <el-form-item label="基准值" prop="collectBaseValuesJson">
                        <v-ace-editor
                                style="
                width: 100%;
                height: 20vh;
                font-size: 16px;
                border: 1px solid;
              "
                                v-model:value="collectForm.data.collectBaseValuesJson!"
                                lang="json"
                                theme="monokai"
                                :options="options"
                        />
                    </el-form-item>
                </el-form>
            </el-scrollbar>

            <template #footer>
                <div
                        style="
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
          "
                >
                    <el-button @click="addOrUpdateCollect" type="primary">确定</el-button>
                    <el-button @click="groupForm.flag = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ref, onBeforeUnmount, onMounted} from "vue";
import {options} from "@/utils/options";
import {VAceEditor} from "vue3-ace-editor";
import "@/assets/aceConfig";
import router from "@/router";
import {
    type ComponentSize,
    type FormInstance,
    type FormRules,
    ElMessage,
} from "element-plus";
import {
    Search,
    EditPen,
    Delete,
    Refresh,
    Plus,
    View,
    Edit,
} from "@element-plus/icons-vue";
import MyPlus from "../../components/icons/MyPlus.vue";
import MyMinus from "@/components/icons/MyMinus.vue";
import MyPlusMinus from "@/components/icons/MyPlusMinus.vue";
import {collectLogAPI} from "../../api/solutionService";
import {getListAPI} from "@/api/temp";
import type {
    GroupList,
    SearchGroupParams,
    GroupForm,
    Group,
    CollectTaskSelectParams,
    CollectTaskList,
    CollectTaskForm,
    CollectTask,
} from "@/model/group";
import {
    GetGroupListApi,
    AddGroupApi,
    UpdateGroupApi,
    DeleteGroupApi,
    GetDataCollectTaskApi,
    AddDataCollectTaskApi,
    UpdateDataCollectTaskApi,
    type CollectTaskUpdateStatus,
    OpenOrCloseDataCollectTaskApi,
    DeleteDataCollectTaskApi,
} from "@/api/group";
import {useRoute} from "vue-router";

onMounted(async () => {
    const savedState = JSON.parse(
        localStorage.getItem("Forward-collectSearchParams")
    );
    if (savedState) {
        Object.assign(collectParams.value, savedState);
    }
    /** 获取组列表 */
    await getGroupList();
    await getTempDataList()
});

onBeforeUnmount(() => {

    localStorage.setItem(
        "Forward-collectSearchParams",
        JSON.stringify({
            pageNum: collectParams.value.pageNum,
            pageSize: collectParams.value.pageSize,
            remark: collectParams.value.remark,
            taskName: collectParams.value.taskName,
            taskType: collectParams.value.taskType,
            taskGroupIds: collectParams.value.taskGroupIds,
        })
    );
})

/** 分组展开开关 */
const allFlag = ref(true);

/** 展开全部分组 */
function openAllIcon() {
    allFlag.value = !allFlag.value;
}

/** 分组列表 */
const groupList = ref<GroupList>([]);

/** 分组表格loading */
const tableLoading = ref(false);

/** 获取组列表搜索参数 */
const searchGroupParams = ref<SearchGroupParams>({
    remark: undefined,
    taskGroupName: undefined,
});

/** 获取组列表方法 */
function getGroupList(): void {
    const groupName = searchGroupParams.value.taskGroupName?.trim();
    tableLoading.value = true;
    GetGroupListApi()
        .then(({data: {list}}) => {
            if (list == null) {
                groupList.value = [];
            } else {
                groupList.value = groupName
                    ? list.filter((v: Group) => v.taskGroupName.includes(groupName))
                    : list;
                /** 获取分组id */
                collectParams.value.taskGroupIds =
                    list.length === groupList.value.length
                        ? [0]
                        : groupList.value.map((v: Group) => v.id!);
            }

            /** 获取数据采集器列表 */
            getCollectList();
        })
        .finally(() => (tableLoading.value = false));
}

/** 分组表单 */
const groupForm = ref<GroupForm>({
    flag: false,
    title: "新增分组",
    data: {
        taskGroupName: "",
    },
    rules: {
        taskGroupName: [
            {
                required: true,
                message: "请输入分组名称",
                trigger: "blur",
            },
        ],
    },
});


const current_row_key = ref(0);


/** 新增|修改分组表单组件实例 */
const groupFormRef = ref();

/**
 * 打开新增或更新分组表单。
 *
 * @param {boolean} flag - 表示是否为更新操作
 * @param {Group} [data] - 分组数据（更新操作时必填）
 */
function openOrUpdateGroupForm(flag: boolean, data?: Group) {
    groupFormRef.value && groupFormRef.value.resetFields();
    groupForm.value = {
        flag: true,
        title: flag ? "新增分组" : "更新分组",
        data: data ? {...data} : {taskGroupName: "", remark: ""},
        rules: groupForm.value.rules,
    };
}

/** 新增或修改分组 */
async function addOrUpdateGroup() {
    if (!groupFormRef.value) return;
    const valid = await groupFormRef.value.validate().catch(() => {
        ElMessage.warning("请按照要求需求填写表单");
        return false;
    });
    if (!valid) return;
    const {title, data} = groupForm.value;
    const apiFunc = title === "新增分组" ? AddGroupApi : UpdateGroupApi;
    const res = await apiFunc(data).finally(() => {
        groupForm.value.flag = false;
        getGroupList();
    });

    // @ts-ignore
    if (res.code === 200) {
        ElMessage.success(title === "新增分组" ? "新增成功" : "更新成功");
    } else {
        ElMessage.error(res.data);
    }
}

/** 删除分组 */
async function deleteGroup(id: number) {
    try {
        const {code, data} = await DeleteGroupApi(id);
        if (code === 200) {
            ElMessage.success(data);
        } else {
            ElMessage.warning(data);
        }
    } finally {
        getGroupList();
    }
}

/** 采集器总数 */
const totalNum = ref<number>();

/** 采集器分页搜索参数 */
const collectParams = ref<CollectTaskSelectParams>({
    pageNum: 1,
    pageSize: 10,
    remark: undefined,
    taskName: undefined,
    taskType: undefined,
    taskGroupIds: undefined,
});

/** 采集器列表 */
const collectList = ref<CollectTaskList>([]);

/** 获取采集器列表 */
async function getCollectList() {
    console.log("获取采集器列表-------------------------------------------");
    if (window["collectGroupId"]) {
        collectParams.value.taskGroupIds = [Number(window["collectGroupId"])];
        window["collectGroupId"] = undefined;
    }
    const {data} = await GetDataCollectTaskApi(collectParams.value);
    data.list &&
    data.list.forEach((x: any) => {
        x.flag = true;
        x.collectBaseValuesJson = JSON.stringify(
            x.collectBaseValuesJson,
            (key, value) => {
                try {
                    return JSON.parse(value);
                } catch (e) {
                    return value;
                }
            },
            2
        );
    });
    // return;
    totalNum.value = data.total;
    collectList.value = data.list ?? [];
}

/** 重重采集器搜索 */
async function reset() {
    collectParams.value.remark = undefined;
    collectParams.value.taskName = undefined;
    collectParams.value.taskType = undefined;
    await getCollectList();
}

/** 采集器表单 */
const collectForm = ref<CollectTaskForm>({
    flag: false,
    title: "新增采集器",
    data: {
        taskName: "", // 采集器名称
        taskType: undefined, // 采集器类型
        taskStatus: undefined, // 采集器状态
        taskFreqCorn: undefined, // 采集器采集频率
        taskOtherInfo: undefined, // 采集器其他信息
        collectFilePath: undefined, // 采集器文件路径
        collectReadLine: undefined, // 采集器读取行数
        taskGroupId: undefined, // 采集器分组
        listenerPort: undefined, // 采集器监听端口
        hexOrderString: undefined, // 采集器十六进制字符串
        tarTcpUrl: undefined, // 转发地址
        taskBufferSize: undefined, // 采集器缓存大小
        clientId: undefined,
        mqttUrl: undefined,
        userName: undefined,
        password: undefined,
        topic: undefined,
        qos: undefined,
        remark: undefined,
        resolveId: undefined,
        handlerId: undefined,
        collectBaseValuesJson: undefined,
    },
    rules: {
        taskName: [
            {
                required: true,
                message: "请输入采集器名称",
                trigger: "blur",
            },
        ],
        taskType: [
            {
                required: true,
                message: "请选择采集方式",
                trigger: "change",
            },
        ],
        listenerPort: [
            {
                required: true,
                type: "number",
                message: "请输入1024-65523之间的整数",
                trigger: "blur",
                min: 1024,
                max: 65523,
            },
        ],
        mqttUrl: [
            {
                required: true,
                message: "请输入有效的MQTT URL，格式为tcp://host:port",
                trigger: "blur",
                pattern: /^tcp:\/\/[^:]+:\d+$/,
            },
        ],
    },
});

/** 采集器状态 */
const collectStatus = ref<CollectTaskUpdateStatus>({
    id: undefined,
    status: undefined,
});
/** 采集器表单组件实例 */
const collectFormRef = ref();

/**
 * 打开新增或更新采集器表单。
 *
 * @param {boolean} flag - 表示是否为更新操作
 * @param {CollectTask} [data] - 采集器数据（更新操作时必填）
 */
function openOrUpdateCollectForm(flag: boolean, data?: CollectTask) {
    if (!flag && data?.taskStatus) {
        ElMessage.warning(`请先停用--"${data.taskName}"--采集器`);
        return;
    }

    collectFormRef.value && collectFormRef.value.resetFields();
    collectForm.value = {
        flag: true,
        title: flag ? "新增采集器" : "更新采集器",
        data: data ? {...data} : {},
        rules: collectForm.value.rules,
    };
}

/** 新增或更新采集器 */
async function addOrUpdateCollect() {
    if (!collectFormRef.value) return;
    const valid = await collectFormRef.value.validate().catch(() => {
        ElMessage.warning("请按照要求需求填写表单");
        return false;
    });
    if (!valid) return;
    const {title, data} = collectForm.value;
    // 转换
    if (title !== "新增采集器") {
        // let obj = JSON.parse(JSON.stringify(data.collectBaseValuesJson));

        const obj = JSON.parse(data.collectBaseValuesJson!);
        // 遍历obj对象的每个key
        for (const key in obj) {
            // 判断key是否是obj对象的自有属性
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                // 将obj[key]从json对象转换为json字符串
                obj[key] = JSON.stringify(obj[key]);
            }
        }

        data.collectBaseValuesJson = JSON.stringify(obj);
        console.log("转换后的数据", data.collectBaseValuesJson);
    }
    const apiFunc =
        title === "新增采集器" ? AddDataCollectTaskApi : UpdateDataCollectTaskApi;
    const res = await apiFunc(data).finally(() => {
        getCollectList();
    });

    // @ts-ignore
    if (res.code === 200) {
        ElMessage.success(title === "新增采集器" ? "新增成功" : "更新成功");
        collectForm.value.flag = false;
    } else {
        ElMessage.error(res.data);
    }
}

/** 开启或关闭采集器 */
async function switchChange(flag: boolean, item: CollectTask) {
    item.flag = false;
    // @ts-ignore
    const {code, data} = await OpenOrCloseDataCollectTaskApi({
        id: item.id,
        status: flag,
    }).finally(() => {
        item.flag = true;
    });

    if (code === 200) {
        ElMessage.success(item.taskName! + (flag ? "开启成功" : "关闭成功"));
    } else {
        ElMessage.error(item.taskName! + data);
    }

    await getCollectList();
}

/** 删除采集器 */
async function deleteCollect(id: number) {
    const res = await DeleteDataCollectTaskApi(id).finally(() => {
        getCollectList();
    });
    // @ts-ignore
    if (res.code === 200) {
        ElMessage.success("删除成功");
    } else {
        ElMessage.error(res.data);
    }
}

/** 分页器组件大小 */
const size = ref<ComponentSize>("default");

/** 是否为分页按钮添加背景色 */
const background = ref(false);

/** 去采集器页面 */
function toCollectPage(id: number, groupId: number) {
    router.push({
        name: "DataCollectView",
        params: {
            id,
            groupId,
        },
    });
}

/** 解析协议模板列表 */
const dataResolverTempList = ref([]);
/** 上报协议模板列表 */
const dataForwardParseTempList = ref([]);
/** 获取解析|上报协议模板 */
const getTempDataList = async () => {
    const {data: {list}} = await getListAPI({
        pageSize: 10000,
        pageNum: 1,
    });

    list.forEach((val: any) => {
        val.type == 1 ? dataResolverTempList.value.push(val) : dataForwardParseTempList.value.push(val)
    })

};
</script>

<style scoped>
.mainDataCollect {
    width: 100%;
    height: 100%;
    display: flex;
    background-color: #fff;

    .left {
        width: 25%;
        height: calc(100% - 40px);
        min-width: 300px;
        max-width: 450px;
        padding: 20px;
    }

    .right {
        flex: 1;
        height: calc(100% - 40px);
        padding: 20px;
        overflow: auto;
        display: flex;
        flex-direction: column;
    }
}

.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
    margin-top: 10px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
    background-color: aqua;
}

.card-header {
    margin: 0;
    padding: 0;
}


</style>

<style scoped>
.el-table__body tr.current-row > td {
    color: #28A458;
    background: #000000 !important;
}
</style>
